//const YG = 'YGLog: ';
class Log {
  TAG = 'YGLog: ';
  timeList = [];
  constructor(opt){
    this.opt = opt || '';
  }
  log(...str){
    this.toLog('log',str)
  }
  info(...str){
    this.toLog('info',str)
  }
  warn(...str){
    this.toLog('warn',str)
  }
  debug(...str){
    this.toLog('debug',str)
  }
  error(...str){
    this.toLog('error',str)
  }
  toLog(name,str){
    console[name](this.joinStr(str))
  }
  joinStr(str){
    str.map((item,index) => {
      if(typeof item == 'object'){
        str[index] = JSON.stringify(item)
      }
    })
    return this.opt + ' ' + this.TAG + str.join(' ');
  }
  time(params) {
    let arr = this.timeList;
    console.error(JSON.stringify(arr)+ '=====')
    let index = this.findElem(arr, 'name', params);
    if(index == -1){
      arr.push({
        name: params,
        start: new Date().getTime()
      })
    } else {
      arr[index].start = new Date().getTime()
    }
  }
  timeEnd(params) {
    let index = this.findElem(this.timeList, 'name', params);
    if(index > -1){
      let endT = new Date().getTime();
      let startT = this.timeList[index].start;
      this.log(`${params} 耗时： ${endT - startT} ms`);
      this.timeList.splice(index,1)
      console.log(this.timeList+'------');
    }
  }

  /**
   * array 要查找的源数组
   * attr 需要查找数组里对象的某个属性值
   * val 需要匹配的值
   */
  findElem(array, attr, val) {
    for (var i = 0; i < array.length; i++) {
      if (array[i][attr] == val) {
        return i; //返回当前索引值
      }
    }
    return -1;
  };
}

export default Log;